package com.xjm.api.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjm.entity.BannerModel;
import com.xjm.entity.vo.PageVo;
import com.xjm.entity.vo.Result;
import com.xjm.service.BannerService;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class BannerController {

    private final BannerService bannerService;

    @GetMapping("/getBanner")
    public Result<PageVo<BannerModel>> list(Long page, Long size){
        if (page == null || page < 1) {
            page = 1L;
        }

        if (size == null || size < 1) {
            size = 5L;
        }
        IPage<BannerModel> paged = bannerService.page(new Page<>(page, size));
        return Result.success(paged);
    }

    @GetMapping("/getBannerById/{id}")
    public Result<BannerModel> getBannerById(@PathVariable("id") Integer id){
        BannerModel bannerModel = bannerService.getById(id);
        return Result.success(bannerModel);
    }

    @PostMapping("/addBanner")
    public Result<Void> addBanner(@RequestBody BannerModel bannerModel){
        String url = bannerModel.getUrl();
        if (StringUtils.isBlank(url)){
            return Result.error("请输入图片地址");
        }
        bannerService.save(bannerModel);
        return Result.success("添加成功");
    }

    @PostMapping("/updateBanner")
    public Result<Void> updateBanner(@RequestBody BannerModel bannerModel){
        String url = bannerModel.getUrl();
        bannerModel.setUpdatedTime(null);
        if (StringUtils.isBlank(url)){
            return Result.error("请输入图片地址");
        }
        bannerService.updateById(bannerModel);
        return Result.success("修改成功");
    }

    /**
     * 删除轮播
     * @param id 管理员id
     */
    @GetMapping("/deleteBanner/{id}")
    public Result<Void> deleteAdmin(@PathVariable("id") Integer id) {
        if (bannerService.removeById(id)) {
            return Result.success("删除轮播成功");
        }
        return Result.error("删除轮播失败");
    }
}
